#!/bin/bash

# 奇迹记录仪一键部署脚本
# Miracle Recorder One-Click Deployment Script

set -e

echo "🚀 开始部署奇迹记录仪..."

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    echo "❌ Docker未安装，请先安装Docker"
    exit 1
fi

if ! command -v docker-compose &> /dev/null; then
    echo "❌ Docker Compose未安装，请先安装Docker Compose"
    exit 1
fi

# 检查端口是否被占用
check_port() {
    local port=$1
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null; then
        echo "❌ 端口 $port 已被占用，请停止占用该端口的进程"
        exit 1
    fi
}

check_port 80
check_port 443
check_port 8080
check_port 5432
check_port 6379
check_port 1935
check_port 8443

echo "✅ 端口检查通过"

# 创建必要的目录
echo "📁 创建必要的目录..."
mkdir -p uploads logs recordings ssl

# 设置权限
chmod 755 uploads logs recordings ssl

# 生成随机密码
DB_PASSWORD=$(openssl rand -base64 32)
JWT_SECRET=$(openssl rand -base64 64)
REDIS_PASSWORD=$(openssl rand -base64 16)

echo "🔐 生成配置文件..."

# 创建环境配置文件
cat > .env << EOF
# 数据库配置
DB_HOST=postgres
DB_PORT=5432
DB_USER=miracle_user
DB_PASSWORD=$DB_PASSWORD
DB_NAME=miracle_recorder

# Redis配置
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_PASSWORD=$REDIS_PASSWORD

# JWT配置
JWT_SECRET=$JWT_SECRET

# AI服务配置
AI_SERVICE_URL=http://ai-service:8000

# 服务器配置
SERVER_PORT=8080
SERVER_RTMP_PORT=1935
SERVER_WEBRTC_PORT=8443
EOF

echo "✅ 环境配置文件创建完成"

# 构建和启动服务
echo "🔨 构建Docker镜像..."
docker-compose build

echo "🚀 启动服务..."
docker-compose up -d

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 30

# 检查服务状态
echo "🔍 检查服务状态..."

# 检查数据库
if docker-compose exec postgres pg_isready -U miracle_user -d miracle_recorder > /dev/null 2>&1; then
    echo "✅ 数据库启动成功"
else
    echo "❌ 数据库启动失败"
    exit 1
fi

# 检查Redis
if docker-compose exec redis redis-cli ping > /dev/null 2>&1; then
    echo "✅ Redis启动成功"
else
    echo "❌ Redis启动失败"
    exit 1
fi

# 检查应用服务
if curl -f http://localhost:8080/health > /dev/null 2>&1; then
    echo "✅ 应用服务启动成功"
else
    echo "❌ 应用服务启动失败"
    exit 1
fi

# 检查Nginx
if curl -f http://localhost/health > /dev/null 2>&1; then
    echo "✅ Nginx启动成功"
else
    echo "❌ Nginx启动失败"
    exit 1
fi

echo ""
echo "🎉 部署成功！"
echo ""
echo "📱 访问地址:"
echo "   Web界面: http://localhost"
echo "   API文档: http://localhost/api/docs"
echo ""
echo "🔧 管理命令:"
echo "   查看日志: docker-compose logs -f"
echo "   停止服务: docker-compose down"
echo "   重启服务: docker-compose restart"
echo "   进入容器: docker-compose exec app bash"
echo ""
echo "📊 服务状态:"
docker-compose ps

echo ""
echo "💡 提示:"
echo "   - 默认管理员账户: admin@miracle.com / password"
echo "   - 配置文件: config.yaml"
echo "   - 上传文件: ./uploads/"
echo "   - 日志文件: ./logs/"
echo ""